package com.okwanshiwu.interceptor;

import com.okwanshiwu.constant.AppConstants;
import com.okwanshiwu.dao.redis.RedisDao;
import com.okwanshiwu.enums.TipEnum;
import com.okwanshiwu.util.MD5;
import com.okwanshiwu.util.TipCode;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * ***********************************************************************************************
 * 版权所有 (C)2016, 北京顺圆科技
 * <p>
 * 文件名称：
 * 内容摘要:
 * 当前版本：
 * 作    者： 
 * 完成日期：
 * 修改记录：
 * 修改日期：
 * 版 本 号：
 * 修 改 人：
 * 修改内容：
 ***********************************************************************************************
 */
public class AppInterceptor implements AsyncHandlerInterceptor{

	private final Logger logger = Logger.getLogger(AppInterceptor.class);

	private final RedisDao rd = RedisDao.getSingleton();

    /**
     * 请求前拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        request.setCharacterEncoding("utf-8");
        String uri = request.getRequestURI();
        logger.debug("app请求的路径：" + uri);
        if(uri.matches(AppConstants.NO_INTERCEPTOR_PATH)){
        	return true;
        }
	    String loginUserToken = rd.get(request.getParameter("loginUser"));//通过获取参数
        if(StringUtils.hasLength(loginUserToken)){
		    String serverSign = MD5.md5(request.getRequestURI().concat(loginUserToken));
			String clientSign = request.getParameter("sign");
			if(serverSign.equals(clientSign)){
				return true;
			}
        }
        TipCode tc = new TipCode(1001,"身份验证失败，请重新登录！");
        response.setCharacterEncoding("utf-8");
		response.getWriter().print(tc.toJson());
	    return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
//        logger.debug("spring拦截器Interceptor的方法afterCompletion");
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        logger.debug("spring拦截器Interceptor的方法afterConcurrentHandlingStarted");
    }
    
}
